import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import 'models/project_config.dart';
import 'services/config_service.dart';

class ProjectConfigPage extends StatefulWidget {
  const ProjectConfigPage({super.key});

  @override
  State<ProjectConfigPage> createState() => _ProjectConfigPageState();
}

class _ProjectConfigPageState extends State<ProjectConfigPage> {
  final _projectFormKey = GlobalKey<FormState>();
  late ConfigService _configService;
  ProjectConfig _config = ProjectConfig();
  bool _isLoading = true;

  // 控制器
  late TextEditingController _projectPathController;
  late TextEditingController _projectNameController;
  late TextEditingController _outputDirController;
  late TextEditingController _versionController;
  late TextEditingController _companyController;
  late TextEditingController _descriptionController;
  late TextEditingController _iconPathController;

  @override
  void initState() {
    super.initState();
    _initializeControllers();
    _loadConfig();
  }

  void _initializeControllers() {
    _projectPathController = TextEditingController();
    _projectNameController = TextEditingController();
    _outputDirController = TextEditingController();
    _versionController = TextEditingController();
    _companyController = TextEditingController();
    _descriptionController = TextEditingController();
    _iconPathController = TextEditingController();
  }

  Future<void> _loadConfig() async {
    _configService = await ConfigService.getInstance();
    final config = await _configService.loadConfig();

    setState(() {
      _config = config;
      _isLoading = false;
    });

    _updateControllers();
  }

  void _updateControllers() {
    _projectPathController.text = _config.projectPath;
    _projectNameController.text = _config.projectName;
    _outputDirController.text = _config.outputDir;
    _versionController.text = _config.version;
    _companyController.text = _config.companyName;
    _descriptionController.text = _config.description;
    _iconPathController.text = _config.iconPath;
  }

  Future<void> _saveConfig() async {
    if (_projectFormKey.currentState!.validate()) {
      final updatedConfig = _config.copyWith(
        projectPath: _projectPathController.text,
        projectName: _projectNameController.text,
        outputDir: _outputDirController.text,
        version: _versionController.text,
        companyName: _companyController.text,
        description: _descriptionController.text,
        iconPath: _iconPathController.text,
      );

      await _configService.saveConfig(updatedConfig);

      setState(() {
        _config = updatedConfig;
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('配置已保存'), backgroundColor: Colors.green),
        );
      }
    }
  }

  Future<void> _resetConfig() async {
    await _configService.clearConfig();

    setState(() {
      _config = ProjectConfig();
    });

    _updateControllers();

    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('配置已重置'), backgroundColor: Colors.orange),
      );
    }
  }

  Future<void> _selectPythonFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['py'],
      dialogTitle: '选择Python主文件',
    );

    if (result != null && result.files.single.path != null) {
      final path = result.files.single.path!;
      _projectPathController.text = path;

      // 自动设置项目名称
      final fileName = path.split(Platform.pathSeparator).last;
      final nameWithoutExtension = fileName.replaceAll('.py', '');
      if (_projectNameController.text.isEmpty) {
        _projectNameController.text = nameWithoutExtension;
      }
    }
  }

  Future<void> _selectOutputDirectory() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath(
      dialogTitle: '选择输出目录',
    );

    if (selectedDirectory != null) {
      _outputDirController.text = selectedDirectory;
    }
  }

  Future<void> _selectIconFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['ico', 'png', 'jpg', 'jpeg'],
      dialogTitle: '选择应用图标',
    );

    if (result != null && result.files.single.path != null) {
      _iconPathController.text = result.files.single.path!;
    }
  }

  @override
  void dispose() {
    _projectPathController.dispose();
    _projectNameController.dispose();
    _outputDirController.dispose();
    _versionController.dispose();
    _companyController.dispose();
    _descriptionController.dispose();
    _iconPathController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Form(
          key: _projectFormKey,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '项目配置',
                  style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 24),

                // 基础配置卡片
                _buildBasicConfigCard(),
                const SizedBox(height: 16),

                // 构建模式卡片
                _buildBuildModeCard(),
                const SizedBox(height: 16),

                // 应用信息卡片
                _buildAppInfoCard(),
                const SizedBox(height: 16),

                // 高级选项卡片
                _buildAdvancedOptionsCard(),
                const SizedBox(height: 24),

                // 操作按钮
                _buildActionButtons(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBasicConfigCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '基础配置',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // Python项目路径
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _projectPathController,
                    decoration: const InputDecoration(
                      labelText: 'Python主文件路径 *',
                      hintText: '选择.py文件',
                      border: OutlineInputBorder(),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请选择Python主文件';
                      }
                      if (!value.endsWith('.py')) {
                        return '请选择有效的Python文件';
                      }
                      return null;
                    },
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectPythonFile,
                  icon: const Icon(Icons.folder_open),
                  label: const Text('浏览'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 项目名称
            TextFormField(
              controller: _projectNameController,
              decoration: const InputDecoration(
                labelText: '项目名称 *',
                hintText: '输入项目名称',
                border: OutlineInputBorder(),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入项目名称';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),

            // 输出目录
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _outputDirController,
                    decoration: const InputDecoration(
                      labelText: '输出目录',
                      hintText: '选择输出目录（可选）',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectOutputDirectory,
                  icon: const Icon(Icons.folder_open),
                  label: const Text('浏览'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBuildModeCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '构建模式',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            RadioListTile<String>(
              title: const Text('独立可执行文件'),
              subtitle: const Text('生成单个可执行文件，包含所有依赖'),
              value: 'standalone',
              groupValue: _config.buildMode,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(buildMode: value);
                });
              },
            ),
            RadioListTile<String>(
              title: const Text('模块'),
              subtitle: const Text('生成Python模块'),
              value: 'module',
              groupValue: _config.buildMode,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(buildMode: value);
                });
              },
            ),
            RadioListTile<String>(
              title: const Text('插件'),
              subtitle: const Text('生成Python插件'),
              value: 'plugin',
              groupValue: _config.buildMode,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(buildMode: value);
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAppInfoCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '应用信息',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _versionController,
                    decoration: const InputDecoration(
                      labelText: '版本号',
                      hintText: '1.0.0',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: TextFormField(
                    controller: _companyController,
                    decoration: const InputDecoration(
                      labelText: '公司名称',
                      hintText: '输入公司名称',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            TextFormField(
              controller: _descriptionController,
              decoration: const InputDecoration(
                labelText: '应用描述',
                hintText: '输入应用描述',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
            const SizedBox(height: 16),

            // 图标文件
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _iconPathController,
                    decoration: const InputDecoration(
                      labelText: '应用图标',
                      hintText: '选择图标文件（可选）',
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: _selectIconFile,
                  icon: const Icon(Icons.image),
                  label: const Text('浏览'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAdvancedOptionsCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '高级选项',
              style: Theme.of(
                context,
              ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            SwitchListTile(
              title: const Text('显示控制台窗口'),
              subtitle: const Text('运行时显示控制台窗口'),
              value: _config.showConsole,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(showConsole: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('启用优化'),
              subtitle: const Text('启用Nuitka优化选项'),
              value: _config.enableOptimization,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(enableOptimization: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('跟踪导入'),
              subtitle: const Text('自动跟踪和包含导入的模块'),
              value: _config.followImports,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(followImports: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('包含数据文件'),
              subtitle: const Text('包含项目中的数据文件'),
              value: _config.includeDataFiles,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(includeDataFiles: value);
                });
              },
            ),
            SwitchListTile(
              title: const Text('调试模式'),
              subtitle: const Text('启用调试信息输出'),
              value: _config.debugMode,
              onChanged: (value) {
                setState(() {
                  _config = _config.copyWith(debugMode: value);
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionButtons() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        OutlinedButton.icon(
          onPressed: _resetConfig,
          icon: const Icon(Icons.refresh),
          label: const Text('重置配置'),
        ),
        const SizedBox(width: 16),
        ElevatedButton.icon(
          onPressed: _saveConfig,
          icon: const Icon(Icons.save),
          label: const Text('保存配置'),
        ),
      ],
    );
  }
}
